﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleExpression
{
    public class JoinEntityExpression : Expression
    {
        private LinkEntityExpressionCollection linkedEntities;
        private EntityMetadata entityMetadata;

        //XML Required
        public JoinEntityExpression()
        { 
        
        }

        public JoinEntityExpression(EntityMetadata entityMetadata)
        {
            this.entityMetadata = entityMetadata;
            this.linkedEntities = new LinkEntityExpressionCollection();
        }

        #region Expression

        public override void Accept(ExpressionVisitor visitor)
        {
            visitor.Visit(this);
        }

        #endregion

        public LinkEntityExpression Add(string entityTo, JoinOperator joinOperator, string fieldFrom, string fieldTo)
        {
            return this.Add(EntityMetadata.GetEntity(entityTo), joinOperator, fieldFrom, fieldTo);
        }

        public LinkEntityExpression Add(EntityMetadata entityMetadata, JoinOperator joinOperator, string fieldFrom, string fieldTo)
        { 
            return this.Add(joinOperator, this.entityMetadata[fieldFrom], entityMetadata[fieldTo]);
        }

        public LinkEntityExpression Add(JoinOperator joinOperator, PropertyMetadata fieldFrom, PropertyMetadata fieldTo)
        {
            fieldTo.EntityMetadata.Alias = string.Format("T{0}", this.LinkedEntities.Count + 1);

            LinkEntityExpression linkEntityExpression = new LinkEntityExpression(joinOperator, fieldFrom, fieldTo);

            this.linkedEntities.Add(linkEntityExpression);

            return linkEntityExpression;
        }

        public LinkEntityExpressionCollection LinkedEntities
        {
            get { return this.linkedEntities; }
        }
    }
}
